using Microsoft.AspNetCore.Mvc;
using MediPlatform.Read.Api.Services;
using MediPlatform.Read.Api.Models;
using MediPlatform.ErrorCode;

namespace MediPlatform.Read.Api.Controllers
{
    /// <summary>
    /// 处方流转订单管理控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class PrescriptionOrderController : ControllerBase
    {
        private readonly PrescriptionOrderService _prescriptionOrderService;
        private readonly ILogger<PrescriptionOrderController> _logger;

        public PrescriptionOrderController(PrescriptionOrderService prescriptionOrderService, ILogger<PrescriptionOrderController> logger)
        {
            _prescriptionOrderService = prescriptionOrderService;
            _logger = logger;
        }

        /// <summary>
        /// 获取处方流转订单分页列表
        /// </summary>
        /// <param name="request">查询请求参数</param>
        /// <returns>分页订单列表</returns>
        [HttpGet("list")]
        public async Task<ActionResult<ApiResult<PrescriptionOrderPagedResponse>>> GetPagedList([FromQuery] PrescriptionOrderQueryRequest request)
        {
            try
            {
                _logger.LogInformation("收到获取处方流转订单分页列表请求，参数：{@Request}", request);

                // 参数验证
                if (request.PageIndex < 1)
                {
                    return BadRequest(ApiResult<PrescriptionOrderPagedResponse>.Error("页码必须大于0"));
                }

                if (request.PageSize < 1 || request.PageSize > 100)
                {
                    return BadRequest(ApiResult<PrescriptionOrderPagedResponse>.Error("每页大小必须在1-100之间"));
                }

                var result = await _prescriptionOrderService.GetPagedListAsync(request);

                _logger.LogInformation("成功获取处方流转订单分页列表，总记录数：{TotalCount}", result.TotalCount);

                return Ok(ApiResult<PrescriptionOrderPagedResponse>.Success(result));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取处方流转订单分页列表失败");
                return StatusCode(500, ApiResult<PrescriptionOrderPagedResponse>.Error("获取订单列表失败：" + ex.Message));
            }
        }

        /// <summary>
        /// 获取处方流转订单详情
        /// </summary>
        /// <param name="id">订单ID</param>
        /// <returns>订单详情</returns>
        [HttpGet("detail/{id}")]
        public async Task<ActionResult<ApiResult<PrescriptionOrderDetailResponse>>> GetDetail(long id)
        {
            try
            {
                _logger.LogInformation("收到获取处方流转订单详情请求，订单ID：{OrderId}", id);

                if (id <= 0)
                {
                    return BadRequest(ApiResult<PrescriptionOrderDetailResponse>.Error("订单ID无效"));
                }

                var result = await _prescriptionOrderService.GetDetailAsync(id);

                if (result == null)
                {
                    return NotFound(ApiResult<PrescriptionOrderDetailResponse>.Error("订单不存在"));
                }

                _logger.LogInformation("成功获取处方流转订单详情，订单ID：{OrderId}", id);

                return Ok(ApiResult<PrescriptionOrderDetailResponse>.Success(result));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取处方流转订单详情失败，订单ID：{OrderId}", id);
                return StatusCode(500, ApiResult<PrescriptionOrderDetailResponse>.Error("获取订单详情失败：" + ex.Message));
            }
        }

        /// <summary>
        /// 获取处方流转订单统计信息
        /// </summary>
        /// <returns>统计信息</returns>
        [HttpGet("statistics")]
        public async Task<ActionResult<ApiResult<PrescriptionOrderStatisticsResponse>>> GetStatistics()
        {
            try
            {
                _logger.LogInformation("收到获取处方流转订单统计信息请求");

                var result = await _prescriptionOrderService.GetStatisticsAsync();

                _logger.LogInformation("成功获取处方流转订单统计信息，总订单数：{TotalCount}", result.TotalCount);

                return Ok(ApiResult<PrescriptionOrderStatisticsResponse>.Success(result));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取处方流转订单统计信息失败");
                return StatusCode(500, ApiResult<PrescriptionOrderStatisticsResponse>.Error("获取统计信息失败：" + ex.Message));
            }
        }

        /// <summary>
        /// 批量删除处方流转订单
        /// </summary>
        /// <param name="ids">订单ID列表</param>
        /// <returns>删除结果</returns>
        [HttpDelete("batch")]
        public async Task<ActionResult<ApiResult<bool>>> BatchDelete([FromBody] List<long> ids)
        {
            try
            {
                _logger.LogInformation("收到批量删除处方流转订单请求，订单ID列表：{OrderIds}", string.Join(",", ids));

                if (ids == null || !ids.Any())
                {
                    return BadRequest(ApiResult<bool>.Error("订单ID列表不能为空"));
                }

                if (ids.Any(id => id <= 0))
                {
                    return BadRequest(ApiResult<bool>.Error("订单ID无效"));
                }

                // 这里应该实现批量删除逻辑
                // 暂时返回成功
                _logger.LogInformation("成功批量删除处方流转订单，订单ID列表：{OrderIds}", string.Join(",", ids));

                return Ok(ApiResult<bool>.Success(true, "批量删除成功"));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量删除处方流转订单失败，订单ID列表：{OrderIds}", string.Join(",", ids));
                return StatusCode(500, ApiResult<bool>.Error("批量删除失败：" + ex.Message));
            }
        }

        /// <summary>
        /// 删除单个处方流转订单
        /// </summary>
        /// <param name="id">订单ID</param>
        /// <returns>删除结果</returns>
        [HttpDelete("{id}")]
        public async Task<ActionResult<ApiResult<bool>>> Delete(long id)
        {
            try
            {
                _logger.LogInformation("收到删除处方流转订单请求，订单ID：{OrderId}", id);

                if (id <= 0)
                {
                    return BadRequest(ApiResult<bool>.Error("订单ID无效"));
                }

                // 这里应该实现删除逻辑
                // 暂时返回成功
                _logger.LogInformation("成功删除处方流转订单，订单ID：{OrderId}", id);

                return Ok(ApiResult<bool>.Success(true, "删除成功"));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除处方流转订单失败，订单ID：{OrderId}", id);
                return StatusCode(500, ApiResult<bool>.Error("删除失败：" + ex.Message));
            }
        }
    }
} 